package com.fjc.service.impl;

import com.fjc.dao.*;
import com.fjc.domain.*;
import com.fjc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by fjc on 2018/9/24.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionMapper permissionMapper;

    public User findUserByUsername(String username){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);
        return list.get(0);
    }

    @Override
    public Set<Role> findUserRoleByUsername(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> list = userMapper.selectByExample(userExample);
        int userId = list.get(0).getId();
        UserRoleExample userRoleExample = new UserRoleExample();
        UserRoleExample.Criteria c = userRoleExample.createCriteria();
        c.andUserIdEqualTo(userId);
        List<UserRole> list1 = userRoleMapper.selectByExample(userRoleExample);
        Set<Role> roleSet = new HashSet<>();
        for (UserRole userRole: list1) {
            roleSet.add(roleMapper.selectByPrimaryKey(userRole.getRoleId()));
        }
        return roleSet;
    }

    @Override
    public Set<Permission> findRolePermissionByRole(Set<Role> roles) {
        Set<Permission> permissions = new HashSet<>();
        for (Role role:roles) {
            RolePermissionExample rolePermissionExample = new RolePermissionExample();
            RolePermissionExample.Criteria criteria = rolePermissionExample.createCriteria();
            criteria.andRoleIdEqualTo(role.getId());
            List<RolePermission> list = rolePermissionMapper.selectByExample(rolePermissionExample);
            for (RolePermission rolePermission:list) {
                permissions.add(permissionMapper.selectByPrimaryKey(rolePermission.getPermissionId()));
            }
        }
        return permissions;
    }
}
